// import 'package:fl_chart_app/presentation/resources/app_resources.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class BloodChart extends StatelessWidget {
  double curveSmoothness = 0.35;
  double barWidth = 2;
  var dashArray = [4, 4];

  Map<int, String> barIndexMap = Map.of({}); //根据这个index 来确定点中的表的值

  FlTitlesData get titlesData2 => FlTitlesData(
    bottomTitles: AxisTitles(sideTitles: bottomTitles),
    rightTitles: AxisTitles(
      sideTitles: SideTitles(
        showTitles: true,
        reservedSize: 30,
        getTitlesWidget: (double value, TitleMeta meta) {
          return SideTitleWidget(
            axisSide: meta.axisSide,
            child: Text(
              "", // meta.formattedValue,
            ),
          );
        },
      ),
    ),
    topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
    leftTitles: AxisTitles(sideTitles: leftTitles()),
  );

  LineTouchData get lineTouchDataCallBack => LineTouchData(
    enabled: true,
    handleBuiltInTouches: true,
    touchTooltipData: LineTouchTooltipData(
      tooltipBgColor: Colors.white,
      tooltipRoundedRadius: 10.r,

      ///曲线表的触摸反馈
      getTooltipItems: (List<LineBarSpot> touchedSpots) {
        debugPrint("tool tip---->>> ${touchedSpots.first.spotIndex} ");
        String label = getTouchedBottomTitle((touchedSpots.first.spotIndex).toDouble());
        var list =
            touchedSpots.map((LineBarSpot touchedSpot) {
              int barIndex = touchedSpot.barIndex; //第几条曲线
              int dataIndex = touchedSpot.spotIndex; //曲线中的第N个数据
              String? dataType = barIndexMap[barIndex]; //数据类型

              // debugPrint("tool tip ${dataType}--->${barIndex}->${dataIndex} ");

              final textStyle = TextStyle(
                color: touchedSpot.bar.gradient?.colors.first ?? touchedSpot.bar.color ?? Colors.blueGrey,
                fontWeight: FontWeight.bold,
                fontSize: 14,
              );

              return LineTooltipItem("${dataType}:" + touchedSpot.y.toInt().toString(), textStyle);
            }).toList();

        // list.add(LineTooltipItem("Time:${label}", GoogleFonts.poppins(
        //   fontSize: 12,
        //   fontWeight: FontWeight.w500,
        //   color: Colors.red
        // )));

        return list;
      },
    ),

    touchCallback: (FlTouchEvent event, LineTouchResponse? r) {
      debugPrint("touch line--->> ${r}");
    },
  );

  List<dynamic> dateList = []; //总数据

  late LineChartData sampleData; //总的表样式数据

  static const String day = "today", week = "week", month = "month", quarter = "quarter", year = "year";

  String dataType; //数据类型

  List<String> xTitles = []; //X 轴的所有坐标值
  List<String> xHasTitles = []; //X 轴的所有坐标值

  var lengends = []; //图例

  BloodChart({super.key, this.dateList = const [], required this.dataType, required this.lengends}) {

    var sysDatas = <FlSpot>[];
    var diaDatas = <FlSpot>[];
    var pulsDatas = <FlSpot>[];

    double minX = double.maxFinite;
    double maxX = double.minPositive;

    xTitles.clear();

    for (int i = 0, isize = dateList.length; i < isize; i++) {
      var data = dateList[i];

      String time = "";

      double xAxis = i.toDouble();

      switch (dataType) {
        case day:
          {
            time = data['recordTime'];
            xTitles.add(time);
            minX = 0;
            maxX = (dateList.length - 1).toDouble();
          }
          break;

        case week:
          {
            time = data['recordTime']??"";
            xTitles.add(time);
            minX = 0;
            maxX = (dateList.length - 1).toDouble();
          }
          break;

        case month:
          {
            time = data['recordTime'] ?? "";
            xTitles.add(time);
            minX = 0;
            maxX = (dateList.length - 1).toDouble();
          }
          break;

        case quarter:
          {
            time = data['week'].toString();
            xTitles.add(time);
            minX = 0;
            maxX = (dateList.length - 1).toDouble();
          }
          break;

        case year:
          {
            time = data['recordTime'] ?? "";
            xTitles.add(time);
            minX = 0;
            maxX = (dateList.length - 1).toDouble();
          }
          break;
      }

      double sysValue = double.parse(data['sys'].toString());
      double diaValue = double.parse(data['dia'].toString());
      double pulseValue = double.parse(data['pulse'].toString());

      if (sysValue != 0) {
        var sysSpot = FlSpot(xAxis, sysValue);
        sysDatas.add(sysSpot);
      }

      if (diaValue != 0) {
        var diaSpot = FlSpot(xAxis, diaValue);
        diaDatas.add(diaSpot);
      }

      if (pulseValue != 0) {
        var pulseSpot = FlSpot(xAxis, pulseValue);
        pulsDatas.add(pulseSpot);
      }

      if (sysValue != 0 && diaValue != 0 && pulseValue != 0) {
        xHasTitles.add(time);
      }
    }

    var lineChartBarDataSys = LineChartBarData(
      isCurved: true,
      curveSmoothness: curveSmoothness,
      color: const Color(0xff7c86f7),
      barWidth: barWidth,
      // dashArray: [1, 1],//虚线框
      isStrokeCapRound: true,
      dotData: FlDotData(
        show: false,
        getDotPainter: (FlSpot spot, double xPercentage, LineChartBarData bar, int index, {double? size}) {
          return FlDotCirclePainter(radius: size, color: const Color(0xff607AE3), strokeColor: const Color(0xff607AE3));
        },
      ),
      belowBarData: BarAreaData(show: false),
      spots: sysDatas,
    );

    var lineChartBarDataDia = LineChartBarData(
      isCurved: true,
      curveSmoothness: curveSmoothness,
      color: const Color(0xffDB9bf9),
      barWidth: barWidth,
      // dashArray: dashArray,
      isStrokeCapRound: true,
      dotData: FlDotData(
        show: false,
        getDotPainter: (FlSpot spot, double xPercentage, LineChartBarData bar, int index, {double? size}) {
          return FlDotCirclePainter(radius: size, color: const Color(0xffC9ADEE), strokeColor: const Color(0xffC9ADEE));
        },
      ),

      belowBarData: BarAreaData(show: false),
      spots: diaDatas,
    );

    var lineChartBarDataPulse = LineChartBarData(
      isCurved: true,
      curveSmoothness: curveSmoothness,
      color: const Color(0xffF2A9C9),
      barWidth: barWidth,
      // dashArray: dashArray,
      isStrokeCapRound: true,
      dotData: FlDotData(
        show: false,
        getDotPainter: (FlSpot spot, double xPercentage, LineChartBarData bar, int index, {double? size}) {
          return FlDotCirclePainter(radius: size, color: const Color(0xffA5AeD6), strokeColor: const Color(0xffA5AeD6));
        },
      ),

      belowBarData: BarAreaData(show: false),
      spots: pulsDatas,
    );

    var barList = <LineChartBarData>[];
    barIndexMap.clear();
    //=======================================================
    for (var lengend in lengends) {
      if (lengend['title'] == "SYS" && lengend['checked'] == true) {
        barIndexMap[barList.length] = "SYS";
        barList.add(lineChartBarDataSys);
      }

      if (lengend['title'] == "DIA" && lengend['checked'] == true) {
        barIndexMap[barList.length] = "DIA";
        barList.add(lineChartBarDataDia);
      }

      if (lengend['title'] == "Pulse" && lengend['checked'] == true) {
        barIndexMap[barList.length] = "Pulse";
        barList.add(lineChartBarDataPulse);
      }
    }
    //=======================================================
    sampleData = LineChartData(
      lineTouchData: lineTouchDataCallBack,
      gridData: gridData,
      titlesData: titlesData2,
      borderData: borderData,
      lineBarsData: barList,
      minX: minX,
      maxX: maxX,
      maxY: 250,
      minY: 0,
    );
  }

  @override
  Widget build(BuildContext context) {
    return LineChart(sampleData, duration: const Duration(milliseconds: 250));
  }

  Widget leftTitleWidgets(double value, TitleMeta meta) {
    const style = TextStyle(fontWeight: FontWeight.bold, fontSize: 12);
    String text = "${value.toInt()}";
    return Text(text, style: style, textAlign: TextAlign.center);
  }

  SideTitles leftTitles() => SideTitles(getTitlesWidget: leftTitleWidgets, showTitles: true, interval: 50, reservedSize: 40);

  Widget bottomTitleWidgets(double value, TitleMeta meta) {
    const style = TextStyle(fontWeight: FontWeight.bold, fontSize: 10);
    Widget text = Text('${getBottomTitle(value)}', style: style);
    return SideTitleWidget(axisSide: meta.axisSide, space: 1, child: text);
  }

  String getLastTwoChars(String str) {
    if (str.length >= 2) {
      return str.substring(str.length - 2);
    } else {
      return str;
    }
  }

  String getBottomTitle(double value) {
    if (xTitles.isEmpty) {
      return "";
    }

    String fullTitle = xTitles[value.toInt()];
    String title = "";

    try {
      switch (dataType) {
        case day:
          {
            //2024-01-01 hh:11:22
            title = fullTitle.substring(10, 13) + ":00";
          }
          break;

        case week:
          {
            // title=fullTitle.substring(5,10);
            title = getWeekdayAbbreviation(fullTitle);
            // text=value.toInt().toString().padLeft(2, "0");
          }
          break;

        case month:
          {
            // text=getLastTwoChars(value.toInt().toString());
            // text=value.toInt().toString();
            title = fullTitle.substring(8, 10);
          }
          break;

        case quarter:
          {
            // title="w"+double.parse(fullTitle).toInt().toString();
            title = "w${int.parse(fullTitle)}";
          }
          break;

        case year:
          {
            // title="w"+double.parse(fullTitle).toInt().toString();
            title = fullTitle.substring(5, 7);
          }
          break;
      }
    } catch (e) {}

    return title;
  }

  String getTouchedBottomTitle(double value) {
    if (xHasTitles.isEmpty) {
      return "";
    }

    String fullTitle = xHasTitles[value.toInt()];

    String title = "";
    switch (dataType) {
      case day:
        {
          //2024-01-01 hh:11:22
          title = "${fullTitle.substring(10, 13)}:00-${(int.parse(fullTitle.substring(10, 13)) + 1)}:00";
        }
        break;

      case week:
        {
          title = fullTitle.substring(5, 10);
          // text=value.toInt().toString().padLeft(2, "0");
        }
        break;

      case month: //已经排除了数据为空的
        {
          title = fullTitle.substring(5, 10);
        }
        break;

      case quarter: //已经排除了数据为空的
        {
          title = "week${double.parse(fullTitle).toInt()}";
        }
        break;

      case year: //已经排除了数据为空的
        {
        }
        break;
    }
    return title;
  }

  int getBottomInterval() {
    int interval = 0;
    switch (dataType) {
      case day:
        {
          interval = 6;
        }
        break;
      case week:
        {
          interval = 1;
        }
        break;
      case month:
        {
          interval = 3;
        }
        break;
      case quarter:
        {
          interval = 1;
        }
        break;
      case year:
        {
          interval = 2;
        }
        break;
    }
    return interval;
  }

  SideTitles get bottomTitles => SideTitles(showTitles: true, reservedSize: 30, interval: getBottomInterval().toDouble(), getTitlesWidget: bottomTitleWidgets);

  FlGridData get gridData => FlGridData(
    show: true,
    drawHorizontalLine: true,
    drawVerticalLine: true,
    getDrawingVerticalLine: (double value) {
      return const FlLine(color: Color(0xfff1f1f1), strokeWidth: 1, dashArray: [8, 4]);
    },
    getDrawingHorizontalLine: (double value) {
      return const FlLine(color: Color(0xfff1f1f1), strokeWidth: 1, dashArray: [8, 4]);
    },
  );

  FlBorderData get borderData => FlBorderData(
    show: true,
    border: const Border(
      bottom: BorderSide(color: Color(0xfff1f1f1), width: 1),
      left: BorderSide(color: Color(0xfff1f1f1), width: 1),
      right: BorderSide(color: Color(0xfff1f1f1), width: 1),
      top: BorderSide(color: Color(0xfff1f1f1), width: 1),
    ),
  );

  String getWeekdayAbbreviation(String dateString) {
    final date = DateTime.parse(dateString); // 例如 "2025-06-13"
    const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    return weekdays[date.weekday - 1];
  }
}
